<template>
    <div class="container">
        <div>
            <button ref="btn" id="btn">切换主题</button>
        </div>
    </div>
</template>

<script setup>
import { ref,onMounted } from 'vue'

//获取按钮dom
const btn = ref()

const toggleTheme = (event)=>{
    //判断当前浏览器是否支持web js 动画 API
    if(!document.startViewTransition){
        document.documentElement.classList.toggle('dark')
        return
    }

    //如果支持我们就使用
    const transition = document.startViewTransition(() => {
        document.documentElement.classList.toggle('dark')
    })

    //在我们动画准备完毕后对我们的新旧页面进行编辑用动画去描绘
    transition.ready.then(() => {
        const { clientX, clientY } = event

        const endRadius = Math.hypot(Math.max(clientX, innerWidth - clientX), Math.max(clientY, innerHeight - clientY))

        const clipPath = [`circle(0px at ${clientX}px ${clientY}px)`, `circle(${endRadius}px at ${clientX}px ${clientY}px)`]

        const isDark = document.documentElement.classList.contains('dark')

        document.documentElement.animate(
            {
              clipPath: isDark ? clipPath.reverse() : clipPath
            },
            {
              duration: 450,
              easing: 'ease-in',
              pseudoElement: isDark ? '::view-transition-old(root)' : '::view-transition-new(root)'
            }
        )
    })
}

onMounted(()=>{
   btn.value.addEventListener('click', function (event) {
        toggleTheme(event)
    }) 
})

</script>

<style>
    html,
    body,
    .container {
        width: 100%;
        height: 100%;
        display: flex;
        flex-direction: column;
        overflow: hidden;
        background-color: #fff;
    }

    button {
        width: 100px;
        height: 30px;
        background-color: #007bff;
        border: none;
        border-radius: 4px;
        color: #fff;
        font-size: 14px;
        cursor: pointer;
        transition: background-color 0.3s ease;
        margin-bottom: 5px;
    }
    button:hover {
        background-color: #0056b3;
    }
    button:active {
        background-color: #e0e0e0;
    }
    /* 对新旧暂时做出显示层级完美的展示我们的动画 */
    ::view-transition-old(root),
    ::view-transition-new(root) {
        animation: none;
        mix-blend-mode: normal;
    }
    ::view-transition-old(root) {
      z-index: 1;
    }
    ::view-transition-new(root) {
      z-index: 2147483646;
    }
    html.dark::view-transition-old(root) {
      z-index: 2147483646;
    }
    html.dark::view-transition-new(root) {
      z-index: 1;
    }
    /* 核心样式 通过滤镜来实现夜间效果 */
    html.dark {
      filter: invert(1) hue-rotate(180deg);

      img,
      video,
      .avatar,
      .image,
      .thumb {
        filter: invert(1) hue-rotate(180deg);
      }
    }
</style>